#!/usr/bin/env python3
import sys
import json
import struct
import yt_dlp
import os

def send_message(message):
    sys.stdout.buffer.write(struct.pack('I', len(message)))
    sys.stdout.buffer.write(message.encode('utf-8'))
    sys.stdout.buffer.flush()

def download_video(video_id, quality):
    url = f'https://www.youtube.com/watch?v={video_id}'
    download_path = os.path.expanduser('~/Downloads/%(title)s.%(ext)s')
    
    ydl_opts = {
        'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
        'outtmpl': download_path,
        'merge_output_format': 'mp4',
        'postprocessors': [{
            'key': 'FFmpegVideoConvertor',
            'preferedformat': 'mp4',
        }],
        'quiet': False,
        'no_warnings': False,
        'progress': True
    }
    
    try:
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            print(f"开始下载视频: {url}")  # 调试信息
            info = ydl.extract_info(url, download=True)
            
            if info:
                return {
                    'status': 'success',
                    'filename': info.get('title', ''),
                    'filepath': os.path.join(os.path.expanduser('~/Downloads'), f"{info.get('title', 'video')}.mp4")
                }
            else:
                return {
                    'status': 'error',
                    'error': '无法获取视频信息'
                }
    except Exception as e:
        print(f"下载出错: {str(e)}")  # 调试信息
        return {
            'status': 'error',
            'error': str(e)
        }

def main():
    while True:
        try:
            raw_length = sys.stdin.buffer.read(4)
            if not raw_length:
                return
            
            message_length = struct.unpack('I', raw_length)[0]
            message = sys.stdin.buffer.read(message_length).decode('utf-8')
            data = json.loads(message)
            
            if data['action'] == 'download':
                result = download_video(data['videoId'], data.get('quality', '720'))
                send_message(json.dumps(result))
        except Exception as e:
            print(f"处理消息出错: {str(e)}")  # 调试信息
            send_message(json.dumps({
                'status': 'error',
                'error': f'处理请求时出错: {str(e)}'
            }))

if __name__ == '__main__':
    main()